package com.zhoujing.myrabbitmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 周敬
 * @version 1.0
 * @createTime 2022/7/19-12:01-星期二
 *
 * 生产者
 * 发送消息
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 开始发送消息
     * @param message 消息
     */
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        log.info("当前时间：{}，发送一条消息给两个TTL队列：{}",new Date().toString(),message);
        rabbitTemplate.convertAndSend("X","XA","消息来自TTL为10s的队列："+message);
        rabbitTemplate.convertAndSend("X","XB","消息来自TTL为40s的队列："+message);
    }

    /**
     * 发送消息并设置过期时间
     * @param message 消息
     * @param expirationTime 过期时间
     */
    @GetMapping("/sendMsg/{message}/{expirationTime}")
    public void sendMsg(@PathVariable String message,@PathVariable Integer expirationTime){
        log.info("当前时间：{}，发送一条消息给一个队列：{}",new Date().toString(),message);

        // 设置过期时间
        MessagePostProcessor messagePostProcessor = msg -> {
            msg.getMessageProperties().setExpiration((expirationTime*1000)+"");
             return msg;
        };

        rabbitTemplate.convertAndSend("X","XC",message,messagePostProcessor);
    }

    /**
     * 基于插件的方式实现延时队列
     * @param message 消息
     * @param expirationTime 过期时间
     */
    @GetMapping("/sendMsgDelayed/{message}/{expirationTime}")
    public void sendMsgDelayed(@PathVariable String message,@PathVariable Integer expirationTime){
      log.info("当前时间：{}，发送一条消息至延时队列：{}，过期时间为：{} 秒",new Date(),message,(expirationTime*1000));

      MessagePostProcessor messagePostProcessor = (msg)->{
        msg.getMessageProperties().setDelay(expirationTime*1000);
        return msg;
      };
      rabbitTemplate.convertAndSend("delayed.exchange","delayed.routingKey",message,messagePostProcessor);
    };

}
